/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: QueryResult.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.client;

import com.gwtext.client.data.*;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.layout.AnchorLayoutData;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.core.EventObject;  
import com.gwtext.client.core.Position;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.*;
import com.google.gwt.xml.client.Node;
	/**
	 * Class to create panel for query result.
	 * Based on the xmlData to create grid.
	 */
public class QueryResult extends Panel {
	private final PDQueryServiceAsync service = GWT.create(PDQueryService.class);
	private String userId = "JIA020";
	private String queryBase64;
	/**
	 * Constructor for QueryResult panel.
	 * @param xmlData xml formated task data.
	 */	
	public QueryResult(String xmlData) {
//		<?xml version="1.0" encoding="UTF-8"?>		
//		<pdsp>
//		<columnsdefinition>
//		<cloumn name="centrelinkid" type="string"/>
//		<cloumn name="firstname" type="string"/>
//		<cloumn name="lastname" type="string"/>
//		<cloumn name="driverid" type="string"/>
//		</columnsdefinition>
//		<record>
//		<centrelinkid>Wan703</centrelinkid>
//		<firstname>Chen</firstname>
//		<lastname>Wang</lastname>
//		<driverid>10871319</driverid>
//		</record>
//		</pdsp>
		
		this.setBorder(false);
		this.setPaddings(5);
		this.setLayout(new FitLayout());		
		GridPanel grid = createGrid(xmlData);
		this.add(grid);
	

	}
	/**
	 * create grid based on the xmlData.
	 * @param xml xmlData for grid.
	 * @return gridPanel.
	 */
	private GridPanel createGrid(String xml) {
		int width = 100;
		int totalwidth = 0;
		com.google.gwt.xml.client.Document doc = XMLParser.parse(xml);
		NodeList nodes = doc.getElementsByTagName(PdspConst.XMLTAG_QUERY);
    Node node = nodes.item(0);
    this.queryBase64 = node.getFirstChild().getNodeValue();
		
		NodeList sections = doc.getElementsByTagName(PdspConst.XMLTAG_COLUMN);
		int numSections = sections.getLength();
		FieldDef[] fieldDef = new FieldDef[numSections];
		ColumnConfig[] columnConfigs = new ColumnConfig[numSections];
		for (int i = 0; i < numSections; i++) {
			Element section = (Element) sections.item(i); // A <sect1>
			String name = section.getAttribute(PdspConst.XMLTAG_NAME);
			String type = section.getAttribute(PdspConst.XMLTAG_TYPE);
			if (type.equalsIgnoreCase("string"))
				fieldDef[i] = new StringFieldDef(name);
			else if (type.equalsIgnoreCase("float"))
				fieldDef[i] = new FloatFieldDef(name);
			else if (type.equalsIgnoreCase("integer"))
				fieldDef[i] = new IntegerFieldDef(name);			
			else if (type.equalsIgnoreCase("boolean"))
				fieldDef[i] = new BooleanFieldDef(name);
			else if (type.equalsIgnoreCase("date"))
				fieldDef[i] = new DateFieldDef(name, name, "m-d-Y");
			columnConfigs[i] = new ColumnConfig(name, name, width, true);
			totalwidth += width;
		}
		RecordDef recordDef = new RecordDef(fieldDef);
		ColumnModel columnModel = new ColumnModel(columnConfigs);

		XmlReader reader = new XmlReader("record", recordDef);
		final Store store = new Store(reader);
		store.loadXmlData(xml, true);

		GridPanel grid = new GridPanel();
		grid.setStore(store);
		grid.setColumnModel(columnModel);
		grid.setTitle("Query Result");
		grid.setWidth(totalwidth + 100);
		grid.setHeight(200);
		grid.stripeRows(true);
		grid.setFrame(true);
		// grid.setAutoExpandColumn("common");
		grid.setIconCls("grid-icon");

		Toolbar toolbar = new Toolbar();  
		ToolbarButton button = new ToolbarButton("Save to tasks", new ButtonListenerAdapter() {  
		    public void onClick(Button button, EventObject e) {  
		    	saveTask();
		    }  
		});  
		toolbar.addButton(button);  
		grid.setBottomToolbar(toolbar);  
		return grid;

	}
	/**
	 * save the task to task queue in server.
	 */	
	private void saveTask() {
		final Window window = new Window();  
		window.setTitle("Description:");  
		window.setWidth(300);  
		window.setHeight(300);  
		window.setMinWidth(300);  
		window.setMinHeight(200);  
		window.setLayout(new FitLayout());  
		window.setPaddings(5);  
		window.setButtonAlign(Position.CENTER);  
		window.setCloseAction(Window.HIDE);  
		window.setPlain(true);  	
		
		FormPanel formPanel = new FormPanel();  
		formPanel.setBaseCls("x-plain");  
		formPanel.setLabelWidth(55);  
		formPanel.setUrl("save-form.php");  
	
		formPanel.setWidth(300);  
		formPanel.setHeight(250);  	
		Label lbDescription = new Label("Please fill description for the task");
		final TextArea taDescription = new TextArea("Description", "description");  
		taDescription.setHideLabel(true);
		taDescription.setWidth(260);
		taDescription.setHeight(180);		
		taDescription.setAllowBlank(false);
		// sets width to 100% and height to "remainder" height - 53px  

		Button btSave = new Button("SaveToTasks"); 
		btSave.addListener(new ButtonListenerAdapter() {  
			public void onClick(Button button, EventObject e) { 
				String description = taDescription.getText();
				if (description == null || description.isEmpty()) {
					MessageBox.alert("Please fill description!");					
					return ;
				}
		    service.saveTask(userId, queryBase64,description,new AsyncCallback<Boolean>(){
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
					  MessageBox.alert("failed:save to my tasks!");
					  window.close();
					}
					@Override
					public void onSuccess(Boolean result) {
						// TODO Auto-generated method stub
						if (result == true)
							MessageBox.alert("Success:save to my tasks!");
						else 
							MessageBox.alert("failed:save to my tasks!");
					  window.close();
					}
		    });		
			}  
			});  
		formPanel.add(lbDescription);
		formPanel.add(taDescription);// new AnchorLayoutData("100% -53"));  	
		formPanel.add(btSave);		
		window.add(formPanel);
		
		window.show();  
	}
}
